﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

using Teigha.DatabaseServices;
using Teigha.Geometry;
using Teigha.Colors;
using Teigha.Export_Import;
using Teigha.GraphicsInterface;
using Teigha.GraphicsSystem;
using Teigha.Runtime;

namespace ExportToDWGTool
{
    //class ProductCheckTab
    //{
    //    public string strType; //类别
    //    public string strName;//名称
    //    public string strLng; //经度
    //    public string strLat; //纬度
    //    public string strDescrip; //描述
    //    public string strBZ;//备注
    //}

    //class MarketCheckTab
    //{
    //    public string strBXH; //表箱号
    //    public string strDBBH;//电表局编号
    //    public string strYHBH; //用户编号
    //    public string strYHMC; //用户名称
    //    public string strCZ; //材质
    //    public string strBW; //表位
    //    public string strDescrip; //描述
    //    public string strBZ;//备注
    //}

    //class FlawTab
    //{
    //    public string strType; //类别
    //    public string strName;//名称
    //    public string strFlaw; //存在缺陷     
    //    public string strDescrip; //描述
    //    public string strBZ;//备注
    //}

    class ReadDataFromExcelZY
    {
        public class GTCheckTab
        {
            public string strType; //类别
            public string strName;//名称
            public string strSSXL;//所属线路
            public string strCZ;//材质
            public string strXZ;//性质
            public string strXH;//型号
            public string strZD;//是否终端
            public string strLng; //经度
            public string strLat; //纬度
            public string strYH;//隐患
            public string strQX; //缺陷
            public string strSL;//数量
            public string strXCRY;//巡查人员
            public string strBZ;//备注
        }

        public class SBCheckTab
        {
            public string strType; //类别
            public string strName;//名称
            public string strSSXL;//所属线路
            public string strZT;//状态
            public string strZC;//资产
            public string strXH;//型号
            public string strRL;//容量
            public string strLng; //经度
            public string strLat; //纬度
            public string strGH;//杆号
            public string strQX; //缺陷
            public string strKH;//开合情况
            public string strYY;//异常原因
            public string strBZ;//备注
        }

        public Dictionary<string, string> m_dicLXCD = new Dictionary<string, string>();

        public Dictionary<string, double> m_dicTJXX = new Dictionary<string, double>();
        //前端
        public List<GDSBInfo> m_listQD = new List<GDSBInfo>();
        //设备名称及信息
        public Dictionary<string, GDSBInfo> m_DicSBInfo = new Dictionary<string, GDSBInfo>();
        //前端,后端设备
        public Dictionary<string, List<GDSBInfo>> m_DicSB = new Dictionary<string, List<GDSBInfo>>();

        public List<GTCheckTab> m_listGTCheck = new List<GTCheckTab>();
      //  public Dictionary<string,List<MarketCheckTab>> m_dictMarket = new Dictionary<string, List<MarketCheckTab>>();

        public List<SBCheckTab> m_listSBCheck = new List<SBCheckTab>();

        public string m_strNM;

        public string m_strBYQType;

        public Database m_pDb = null;

        public double m_xMin = 0;
        public double m_xMax = 0;
        public double m_yMin = 0;
        public double m_yMax = 0;

        public double d = 10;

        public string m_strPath;

        private string SetSBNameByType(string strType, string strXZ)
        {
            switch (strType)
            {              
                case "tower":
                    {                      
                        if(strXZ == "耐张")
                        {
                            return "zy_nz";
                        } 
                        else
                            return "zy_zx";
                    }
                case "bdz":
                    return "zy_bdz";
            }

            return strType;
        }

        private string SetSBLBByType(string strType,string strCZ)
        {
            switch (strType)
            {
                case "bdz":
                    return "变电站";
                case "tower":
                    {
                        if(string.IsNullOrEmpty(strCZ))
                        {
                            return "杆塔";
                        }
                        else
                            return strCZ;
                    }
                case "zy_dlskg":
                    return "跌落式开关";
                case "zy_fzx":
                    return "电缆分支箱";
                case "zy_gd":
                    return "拐点";
                case "zy_gybyq":
                    return "公用变压器";
                case "zy_hwg":
                    return "环网柜";
                case "zy_jgt":
                    return "角钢塔";
                case "zy_kbz":
                    return "开闭站";
                case "zy_pds":
                    return "配电室";               
                case "zy_xb":
                    return "箱式变压器";
                case "zy_zhkg_h":
                    return "柱上开关合";
                case "zy_zskg_k":
                    return "柱上开关分";
                case "zy_zybyq":
                    return "专用变压器";
                    
            }

            return "zd";
        }

        public bool ReadSBInfoExcel(string strPath)
        {
            try
            {
                IWorkbook pWb = NPOIExcelHelper.OpenWorkbook(strPath);
                ISheet pSt = NPOIExcelHelper.FirstOrDefaultWorksheetNameStartWith(pWb, "");

                var lines = NPOIExcelHelper.ReadLines(pSt, 1, 0, 0);
                m_strNM = lines[0][0];

                lines = NPOIExcelHelper.ReadLines(pSt, 0, 0,3);
                NPOIExcelHelper.CloseWorkbook(pWb);
               
                for (int i = 0;i<lines.Count;i++)
                {
                    string[] strList = lines[i];
                   
                    GDSBInfo pInfo = new GDSBInfo();
                    pInfo.strMC = strList[1];
                    if(string.IsNullOrEmpty(strList[9]))
                    {
                        pInfo.lng = 0;
                    }
                    else
                    {
                        pInfo.lng = double.Parse(strList[9]);
                    }
                    if(string.IsNullOrEmpty(strList[10]))
                    {
                        pInfo.lat = 0;
                    }
                    else
                    {
                        pInfo.lat = double.Parse(strList[10]);
                    }
                    pInfo.strLineTp = strList[15];
                    pInfo.strLY = SetSBNameByType(strList[5], strList[6]);
                    pInfo.strLineType = strList[16];
                    pInfo.strCZ = strList[4];
                    pInfo.strXZ = strList[6];

                    if (m_dicTJXX.Keys.Contains(strList[5]))
                    {
                        double nSize = m_dicTJXX[strList[5]];
                        m_dicTJXX[strList[5]]= nSize+1;
                    }
                    else
                    {
                        m_dicTJXX.Add(strList[5],1);
                    }

                    if (!m_DicSBInfo.Keys.Contains(pInfo.strMC))
                    {
                        m_DicSBInfo.Add(pInfo.strMC, pInfo);
                    }

                    if (strList[5]=="bdz")
                    {
                        m_listQD.Add(pInfo);

                        SBCheckTab sbCheck = new SBCheckTab();
                        sbCheck.strName = strList[1];
                        sbCheck.strLng = strList[9];
                        sbCheck.strLat = strList[10];
                        sbCheck.strType = SetSBLBByType(strList[5], strList[4]);

                        sbCheck.strSSXL = strList[3];

                        sbCheck.strXH = strList[7];

                        sbCheck.strQX = strList[12];

                        m_listSBCheck.Add(sbCheck);

                        continue;
                    }

                    string strQD = strList[2];

                    if (m_DicSB.Keys.Contains(strQD))
                    {
                        List<GDSBInfo> list = m_DicSB[strQD];
                        list.Add(pInfo);
                        m_DicSB[strQD]= list;
                    }
                    else
                    {
                        List<GDSBInfo> list = new List<GDSBInfo>();
                        list.Add(pInfo);
                        m_DicSB.Add(strQD,list);
                    }

                    //*************************************************

                    if(strList[5]== "tower")
                    {
                        GTCheckTab pProduct = new GTCheckTab();
                        pProduct.strName = strList[1];
                        pProduct.strLng = strList[9];
                        pProduct.strLat = strList[10];
                        pProduct.strType = SetSBLBByType(strList[5],strList[4]);
                       
                        //pProduct.strXH = strList[7];
                        pProduct.strSSXL = strList[3];
                        pProduct.strCZ = strList[4];
                        pProduct.strXZ = strList[6];
                        pProduct.strXH = strList[7];
                        pProduct.strZD = strList[8];
                        pProduct.strYH = strList[11];
                        pProduct.strQX = strList[12];
                        pProduct.strSL = strList[13];
                        pProduct.strXCRY = strList[14];

                        m_listGTCheck.Add(pProduct);
                    }
                    else
                    {
                        SBCheckTab pProduct = new SBCheckTab();
                        pProduct.strName = strList[1];
                        pProduct.strLng = strList[9];
                        pProduct.strLat = strList[10];
                        pProduct.strType = SetSBLBByType(strList[5], strList[4]);
                  
                        pProduct.strSSXL = strList[3];
             
                        pProduct.strXH = strList[7];
                
                        pProduct.strQX = strList[12];
                    

                        m_listSBCheck.Add(pProduct);
                    }
                }
            }
            catch (System.Exception ex)
            {
                return false;
            }

            return true;
        }     

        public bool SaveToDWG(string strTempDWG, string strOutSave)
        {
            try
            {
                System.DateTime time = System.DateTime.Now;

                // LogManageMt.m_listLog.Add("时间：" + time.ToString() + "   开始转换，请等待……");
                m_strPath = strOutSave;
               string strOutDWG = strOutSave + "\\"+m_strNM+".DWG";
                if (File.Exists(strOutSave))
                {
                    File.Delete(strOutSave);
                }

                using (Database pDb = new Database(false, false))// 加参数出错
                {
                    pDb.ReadDwgFile(strTempDWG, FileOpenMode.OpenForReadAndWriteNoShare, false, "");

                    // LogManageMt.m_listLog.Add("开始将转换对象添加到模型空间，请等待……");
                    m_pDb = pDb;

                    BlockTableRecord btr = (BlockTableRecord)pDb.CurrentSpaceId.GetObject(OpenMode.ForWrite);
  
                    for (int i = 0;i< m_listQD.Count;i++)
                    {
                        GDSBInfo pInfo = m_listQD[i];
                        string strQD = pInfo.strMC;
                        if(pInfo.strLY== "zy_bdz")
                        {
                            CreateBDZ(btr, pInfo);
                        }
                        else
                        {
                            Point2d ptS = Point2d.Origin;
                            Point2d ptE = Point2d.Origin;
                            CreateSB(btr, pInfo, ref ptE, ref ptS);
                            CreatePLine(btr, strQD, ptE);
                        }
                      
                    }

                    if (m_listQD.Count > 0 )
                    {
                        Teigha.DatabaseServices.Polyline pLine = CreateTK(m_xMin,m_xMax,m_yMin,m_yMax);
                        btr.AppendEntity(pLine);

                        Point3d pt = new Point3d((m_xMin + m_xMax)/2,m_yMax + d+3, 0);
                        DBText pText = CreateText(pt, m_strNM, "宋体");
                        ObjectId OId = btr.AppendEntity(pText);
                        pText = OId.GetObject(OpenMode.ForWrite) as DBText;
                        pText.Height = 3.0;
                        //pText.HorizontalMode = TextHorizontalMode.TextCenter;
                        //pText.VerticalMode = TextVerticalMode.TextVerticalMid;


                        //添加块参照
                        ObjectId BlkId = GetBlkIdByName(pDb, "zbz");
                        if (BlkId != ObjectId.Null)
                        {
                            Point3d pt3D = new Point3d(m_xMax +d - 6, m_yMax+d -10, 0);
                            BlockReference blkRef = new BlockReference(pt3D, BlkId);
                            ObjectId Id = btr.AppendEntity(blkRef);

                        }

                        BlkId = GetBlkIdByName(pDb, "TL");
                        if (BlkId != ObjectId.Null)
                        {
                            //BlockTableRecord pBlock = BlkId.GetObject(OpenMode.ForWrite) as BlockTableRecord; 

                            //Point3d ptText = new Point3d(-7,5.5, 0);
                            //DBText pTNM = CreateText(ptText, m_strNM, "宋体");
                            //pTNM.Height = 0.6;
                            ////pTNM.VerticalMode = TextVerticalMode.TextVerticalMid;
                            ////pTNM.HorizontalMode = TextHorizontalMode.TextCenter;
                            //pBlock.AppendEntity(pTNM);

                            Point3d pt3D = new Point3d(m_xMin-d+1, m_yMin-d+1, 0);
                            BlockReference blkRef = new BlockReference(pt3D, BlkId);
                            blkRef.ScaleFactors = new Scale3d(0.1,0.1,0.1);
                            ObjectId Id = btr.AppendEntity(blkRef);

                        }

                        BlkId = GetBlkIdByName(pDb, "TM");
                        if (BlkId != ObjectId.Null)
                        {
                            BlockTableRecord pBlock = BlkId.GetObject(OpenMode.ForWrite) as BlockTableRecord;

                            Point3d ptText = new Point3d(-66, 23, 0);
                            DBText pTNM = CreateText(ptText, m_strNM, "宋体");
                            pTNM.Height = 6.75;
                            pTNM.VerticalMode = TextVerticalMode.TextBottom;
                            pTNM.HorizontalMode = TextHorizontalMode.TextCenter;
                            pBlock.AppendEntity(pTNM);

                            Point3d pt3D = new Point3d(m_xMax + 1, m_yMin - d + 1, 0);
                            BlockReference blkRef = new BlockReference(pt3D, BlkId);
                            blkRef.ScaleFactors = new Scale3d(0.1, 0.1, 0.1);
                            ObjectId Id = btr.AppendEntity(blkRef);

                        }

                        BlkId = GetBlkIdByName(pDb, "CLXX");
                        if (BlkId != ObjectId.Null)
                        {
                            double dXL = GetTJSL("导线");
                            double dGT = GetTJSL("tower");
                            double dKG = GetTJSL("kg");
                            double dGYB = GetTJSL("gybyq");
                            double dBDZ = GetTJSL("bdz");

                            BlockTableRecord pBlock = BlkId.GetObject(OpenMode.ForWrite) as BlockTableRecord;

                            Point3d ptText = new Point3d(-104, -34, 0);
                            DBText pTDX = CreateText(ptText, dXL.ToString("f2"), "宋体");
                            pTDX.Height = 13.5;
                            pTDX.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pTDX.HorizontalMode = TextHorizontalMode.TextLeft;
                            pBlock.AppendEntity(pTDX);

                             ptText = new Point3d(-83, -90, 0);
                            DBText pTGT = CreateText(ptText, dGT.ToString("f0"), "宋体");
                            pTGT.Height = 13.5;
                            pTGT.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pTGT.HorizontalMode = TextHorizontalMode.TextCenter;
                            pBlock.AppendEntity(pTGT);

                            ptText = new Point3d(-83, -153.5, 0);
                            DBText pTKG = CreateText(ptText, dKG.ToString("f0"), "宋体");
                            pTKG.Height = 13.5;
                            pTKG.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pTKG.HorizontalMode = TextHorizontalMode.TextCenter;
                            pBlock.AppendEntity(pTKG);

                            ptText = new Point3d(-83, -209, 0);
                            DBText pTGYB = CreateText(ptText, dGYB.ToString("f0"), "宋体");
                            pTGYB.Height = 13.5;
                            pTGYB.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pTGYB.HorizontalMode = TextHorizontalMode.TextCenter;
                            pBlock.AppendEntity(pTGYB);

                            ptText = new Point3d(-83, -269, 0);
                            DBText pTBDZ = CreateText(ptText, dBDZ.ToString("f0"), "宋体");
                            pTBDZ.Height = 13.5;
                            pTBDZ.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pTBDZ.HorizontalMode = TextHorizontalMode.TextCenter;
                            pBlock.AppendEntity(pTBDZ);


                            Point3d pt3D = new Point3d(m_xMax + 1, m_yMax -d + 1, 0);
                            BlockReference blkRef = new BlockReference(pt3D, BlkId);
                            blkRef.ScaleFactors = new Scale3d(0.1, 0.1, 0.1);
                            ObjectId Id = btr.AppendEntity(blkRef);

                        }

                        SaveType pSavetype = SaveType.Save12; //Save12 为.dwg Save13 为dxf

                        DwgVersion dwgver = DwgVersion.vAC21; //ACAD2010为 vAC24； ACAD2007 为 vAC21； ACAD2004为vAC18；

                        pDb.SaveAs(@strOutDWG, dwgver);
                    }

                       time = System.DateTime.Now;
                    // LogManageMt.m_listLog.Add("时间：" + time.ToString() + "   转换完成！"); 

                }

                string strOutExcel = strOutSave + "\\中压线路核查表(" + m_strNM + ").xls";
                SaveToExcel(@strOutExcel);

                return true;
            }
            catch (System.Exception ex)
            {
                System.DateTime time = System.DateTime.Now;
                // LogManageMt.m_listLog.Add("时间：" + time.ToString() + "   错误信息：" + ex.Message);
                MessageBox.Show(ex.Message);

                return false;
            }
        }

        private double GetTJSL(string strLX)
        {
            double dCount = 0;
            try
            {
                foreach(string key in m_dicTJXX.Keys)
                {
                    if (key.Contains(strLX))
                    {
                        dCount += m_dicTJXX[key];
                    }                   
                }
            }
            catch (System.Exception)
            {
              
            }
            return dCount;
        }
        private Teigha.DatabaseServices.Polyline CreateTK(double xMin, double xMax, double yMin, double yMax)
        {
            Teigha.DatabaseServices.Polyline pLine = null;
            try
            {
                pLine = new Teigha.DatabaseServices.Polyline();
                pLine.AddVertexAt(0, new Point2d(xMin-d, yMin - d), 0, 0, 0);
                pLine.AddVertexAt(1, new Point2d(xMax+d, yMin - d), 0, 0, 0);
                pLine.AddVertexAt(2, new Point2d(xMax + d, yMax + d), 0, 0, 0);
                pLine.AddVertexAt(3, new Point2d(xMin - d, yMax + d), 0, 0, 0);

                pLine.Closed = true;

            }
            catch (System.Exception ex)
            {
                return null;
            }

            return pLine;
        }

        private bool CreateBDZ(BlockTableRecord btr, GDSBInfo pInfo)
        {
            try
            {
                double x = 0;
                double y = 0;

                ConvertPlaneCoord.MCT84Bl2xy(pInfo.lng, pInfo.lat, out x, out y);

                Entity pwEnt = null;

                //添加配电箱图标
                //添加块参照
                ObjectId BlkId0 = GetBlkIdByName(m_pDb, "zy_bdz");
                if (BlkId0 == ObjectId.Null)
                {
                    BlkId0 = GetBlkIdByName(m_pDb, "zd");
                }

                Point3d pt3D0 = new Point3d(y, x, 0);
                BlockReference blkRef0 = new BlockReference(pt3D0, BlkId0);
                ObjectId Id = btr.AppendEntity(blkRef0);

                GetExtent(blkRef0, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                pwEnt = null;
                if (FindCADLayerByNM(m_pDb, "电力设备") == true)
                {
                    pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                    pwEnt.Layer = "电力设备";


                    HyperLinkCollection linkCollection = pwEnt.Hyperlinks;

                    //Create a new hyperlink

                    string strlinkPath = "配电设备\\" + pInfo.strMC + "全貌.jpg";

                    HyperLink hyperLink = new HyperLink();

                    hyperLink.Description = strlinkPath;

                    hyperLink.Name = strlinkPath;

                    hyperLink.SubLocation = strlinkPath;

                    //Add the hyperlink to the collection

                    linkCollection.Add(hyperLink);

                }

                Point3d pt3dText0 = new Point3d(y, x + 0.8, 0);
                DBText pText0 = CreateText(pt3dText0, pInfo.strMC, "宋体");

                pText0.HorizontalMode = TextHorizontalMode.TextMid;
                pText0.VerticalMode = TextVerticalMode.TextVerticalMid;
                pText0.Height = 1;

                Id = btr.AppendEntity(pText0);
                GetExtent(pText0, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                if (FindCADLayerByNM(m_pDb, "设备名称") == true)
                {
                    pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                    pwEnt.Layer = "设备名称";

                    HyperLinkCollection linkCollection = pwEnt.Hyperlinks;

                    //Create a new hyperlink

                    string strlinkPath = "配电设备\\" + pInfo.strMC + "铭牌.jpg";

                    HyperLink hyperLink = new HyperLink();

                    hyperLink.Description = strlinkPath;

                    hyperLink.Name = strlinkPath;

                    hyperLink.SubLocation = strlinkPath;

                    //Add the hyperlink to the collection

                    linkCollection.Add(hyperLink);
                }

                CreatePLine(btr, pInfo.strMC, new Point2d(y, x));


            }
            catch (System.Exception ex)
            {
                return false;
            }
            return true;
        }

        //配电箱及开关设置
        private bool CreatePDX(BlockTableRecord btr, GDSBInfo pInfo)
        {
            try
            {
                double x = 0;
                double y = 0;

                ConvertPlaneCoord.MCT84Bl2xy(pInfo.lng, pInfo.lat, out x, out y);

                Point2d pt0 = new Point2d(y - 1.3, x + 1.3);
                Point2d pt1 = new Point2d(y + 1.3, x + 1.3);
                Point2d pt2 = new Point2d(y + 1.3, x - 1.3);
                Point2d pt3 = new Point2d(y - 1.3, x - 1.3);

                Teigha.DatabaseServices.Polyline pLine = new Teigha.DatabaseServices.Polyline();
                pLine.AddVertexAt(0, pt0, 0, 0, 0);
                pLine.AddVertexAt(1, pt1, 0, 0, 0);
                pLine.AddVertexAt(2, pt2, 0, 0, 0);
                pLine.AddVertexAt(3, pt3, 0, 0, 0);
                pLine.Closed = true;

                ObjectId Id = btr.AppendEntity(pLine);
                GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                Entity pwEnt = null;
                if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                {
                    pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                    pwEnt.Layer = "KGXL1";
                   // pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                }

                if (m_DicSB.Keys.Contains(pInfo.strMC))
                {
                    List<GDSBInfo> list = m_DicSB[pInfo.strMC];

                    int n = list.Count;
                    double d = 2.6/(n+1);

                    pLine = new Teigha.DatabaseServices.Polyline();
                    pLine.AddVertexAt(0, new Point2d(pt0.X+d,pt0.Y-0.5), 0, 0, 0);
                    pLine.AddVertexAt(1, new Point2d(pt1.X-d,pt0.Y-0.5), 0, 0, 0);
                    Id = btr.AppendEntity(pLine);
                    GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    pwEnt = null;
                    if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = "KGXL1";
                       // pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                    }

                    //添加配电箱图标

                    pLine = new Teigha.DatabaseServices.Polyline();
                    pLine.AddVertexAt(0, new Point2d(y, x +0.8), 0, 0, 0);
                    pLine.AddVertexAt(1, new Point2d(y, x +2.5), 0, 0, 0);
                    Id = btr.AppendEntity(pLine);
                    GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);
                     pwEnt = null;
                    if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = "KGXL1";

                    }

                    //添加块参照
                    ObjectId BlkId0 = GetBlkIdByName(m_pDb, "GDBYQ");
                    if (BlkId0 == ObjectId.Null)
                    {
                        BlkId0 = GetBlkIdByName(m_pDb, "zd");
                    }

                    Point3d pt3D0 = new Point3d(y, x + 2.5, 0);
                    BlockReference blkRef0 = new BlockReference(pt3D0, BlkId0);
                    Id = btr.AppendEntity(blkRef0);
                    GetExtent(blkRef0, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    pwEnt = null;
                    if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = "KGXL1";
                    }

                    Point3d pt3dText0 = new Point3d(y, x + 3.8, 0);
                    DBText pText0 = CreateText(pt3dText0,m_strNM, "宋体");

                    pText0.HorizontalMode = TextHorizontalMode.TextMid;
                    pText0.VerticalMode = TextVerticalMode.TextVerticalMid;
                    pText0.Height = 0.15;

                    Id = btr.AppendEntity(pText0);
                    GetExtent(pText0, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = "KGXL1";
                    }

                    //*******************************************************

                    List<Dictionary<string, Point2d>> listZ = new List<Dictionary<string, Point2d>>();
                    List<Dictionary<string, Point2d>> listY = new List<Dictionary<string, Point2d>>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        GDSBInfo p = list[i];

                        pLine = new Teigha.DatabaseServices.Polyline();
                        pLine.AddVertexAt(0, new Point2d(pt0.X + d*(i+1), pt0.Y - 0.5), 0, 0, 0);
                        pLine.AddVertexAt(1, new Point2d(pt0.X + d * (i + 1), pt0.Y-1.05), 0, 0, 0);
                        Id = btr.AppendEntity(pLine);
                        GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                        pwEnt = null;
                        if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = "KGXL1";
                           // pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                        }

                        //添加块参照
                        ObjectId BlkId = GetBlkIdByName(m_pDb, "GDPDKG");
                        if (BlkId == ObjectId.Null)
                        {
                            BlkId = GetBlkIdByName(m_pDb, "zd");
                        }

                        Point3d pt3D = new Point3d(pt0.X + d*(i+1), pt0.Y-1.7334, 0);
                        BlockReference blkRef = new BlockReference(pt3D, BlkId);
                        Id = btr.AppendEntity(blkRef);
                        GetExtent(blkRef, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                        pwEnt = null;
                        if (FindCADLayerByNM(m_pDb, pInfo.strLY) == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = "GDPDKG";
                        }

                        Dictionary<string, Point2d> dicZ = new Dictionary<string, Point2d>();
                        Dictionary<string, Point2d> dicY = new Dictionary<string, Point2d>();

                        if (m_DicSB.Keys.Contains(p.strMC))
                        {
                            Point3d pt3dText = new Point3d(pt0.X + d * (i + 1)+0.1, pt0.Y - 1.7334, 0);
                            DBText pText = CreateText(pt3dText, p.strMC, "宋体");

                            pText.HorizontalMode = TextHorizontalMode.TextMid;
                            pText.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pText.Height = 0.08;
                            pText.Rotation = 270 * Math.PI / 180;

                            Id = btr.AppendEntity(pText);
                            GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                            if (FindCADLayerByNM(m_pDb, pInfo.strLY) == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = pInfo.strLY;                               
                            }

                            pLine = new Teigha.DatabaseServices.Polyline();
                            pLine.AddVertexAt(0, new Point2d(pt0.X + d * (i + 1), pt0.Y - 2.27), 0, 0, 0);
                            pLine.AddVertexAt(1, new Point2d(pt0.X + d * (i + 1), pt0.Y - 3.5), 0, 0, 0);
                            Id = btr.AppendEntity(pLine);
                            GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                            pwEnt = null;
                            if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = "KGXL1";
                               // pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);

                            }
                            GDSBInfo pp = m_DicSB[p.strMC][0];
                            double px = 0;
                            double py = 0;

                            ConvertPlaneCoord.MCT84Bl2xy(pp.lng, pp.lat, out px, out py);

                            if(pt0.X + d * (i + 1)>= py)
                            {
                                if (!dicZ.Keys.Contains(p.strMC))
                                {
                                    dicZ.Add(p.strMC, new Point2d(pt0.X + d * (i + 1), pt0.Y - 3.5));
                                }
                            }
                            else
                            {
                                if (!dicY.Keys.Contains(p.strMC))
                                {
                                    dicY.Add(p.strMC, new Point2d(pt0.X + d * (i + 1), pt0.Y - 3.5));
                                }
                            }

                        

                            //int m = 0;
                            //if(n%2==1)
                            //{
                            //    m = (n + 1) / 2;
                            //}
                            //else
                            //{
                            //    m = n/ 2;
                            //}

                            //if (i >= m)
                            //{
                            //    CreateKGSB(btr, dic, xOffY, "右", yOffY);

                            //    yOffY = yOffY - 0.3;
                            //    xOffY = xOffY + d;
                            //}
                            //else
                            //{
                            //    CreateKGSB(btr, dic, xOffZ, "左", yOffZ);
                            //    yOffZ = yOffZ - 0.3;
                            //    xOffZ = xOffZ - d;
                            //}
                        }
                        else
                        {
                            Point3d pt3dText = new Point3d(pt0.X + d * (i + 1) + 0.1, pt0.Y - 1.7334, 0);
                            DBText pText = CreateText(pt3dText, p.strMC+"(备用)", "宋体");

                            pText.HorizontalMode = TextHorizontalMode.TextMid;
                            pText.VerticalMode = TextVerticalMode.TextVerticalMid;
                            pText.Rotation = 270 * Math.PI / 180;
                            pText.Height = 0.08;
                            Id = btr.AppendEntity(pText);
                            GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                            if (FindCADLayerByNM(m_pDb, pInfo.strLY) == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = pInfo.strLY;
                            }
                        }

                        if(dicZ.Count>0)
                        {                         
                            listZ.Add(dicZ);
                        }

                        if (dicY.Count > 0)
                        {
                            listY.Add(dicY);
                        }

                    }

                    double yOffZ = 0;
                    double yOffY = 0;
                    double xOffZ = -2;
                    double xOffY = 2;

                    for (int i = 0;i<listZ.Count;i++)
                    {
                        Dictionary<string, Point2d> dic = listZ[i];
                        CreateKGSB(btr, dic, xOffZ, "左", yOffZ);
                        yOffZ = yOffZ - 0.3;
                        xOffZ = xOffZ - d;
                    }

                    for (int i = 0; i < listY.Count; i++)
                    {
                        Dictionary<string, Point2d> dic = listY[i];
                        CreateKGSB(btr, dic, xOffY, "右", yOffY);

                        yOffY = yOffY - 0.3;
                        xOffY = xOffY + d;
                    }
                }

            }
            catch(System.Exception ex)
            {
                return false;
            }
            return true;
       }

        private bool CreateKGSB(BlockTableRecord btr, Dictionary<string, Point2d> dic,double jj,string strFX, double yOff)
        {
            try
            {
                if (strFX == "左")
                {
                    double xOff = -2;
                    foreach (string str in dic.Keys)
                    {
                        Point2d pt = dic[str];

                        Point2d pt0 = new Point2d(pt.X, pt.Y + yOff);
                        Point2d pt1 = new Point2d(pt.X + xOff, pt.Y + yOff);
                        Teigha.DatabaseServices.Polyline pLine = new Teigha.DatabaseServices.Polyline();
                        pLine.AddVertexAt(0, pt, 0, 0, 0);
                        pLine.AddVertexAt(1, pt0, 0, 0, 0);
                        pLine.AddVertexAt(2, pt1, 0, 0, 0);

                        ObjectId Id = btr.AppendEntity(pLine);
                        GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                        Entity pwEnt = null;
                        if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = "KGXL1";
                           // pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                        }

                        CreatePLine(btr, str, pt1);

                        xOff = xOff + jj;
                    }
                }
                else
                {
                    double xOff = 2;

                    foreach (string str in dic.Keys)
                    {
                        Point2d pt = dic[str];

                        Point2d pt0 = new Point2d(pt.X, pt.Y + yOff);
                        Point2d pt1 = new Point2d(pt.X + xOff, pt.Y + yOff);
                        Teigha.DatabaseServices.Polyline pLine = new Teigha.DatabaseServices.Polyline();
                        pLine.AddVertexAt(0, pt, 0, 0, 0);
                        pLine.AddVertexAt(1, pt0, 0, 0, 0);
                        pLine.AddVertexAt(2, pt1, 0, 0, 0);

                        ObjectId Id = btr.AppendEntity(pLine);
                        GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                        Entity pwEnt = null;
                        if (FindCADLayerByNM(m_pDb, "KGXL1") == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = "KGXL1";
                           // pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                        }

                        CreatePLine(btr, str, pt1);

                    }

                }

            }
            catch(System.Exception ex)
            {
                return false;
            }

            return true;
        }

        private bool CreatePLine(BlockTableRecord btr,string strQD, Point2d ptS)
        {
            try
            {
                if (m_DicSB.Keys.Contains(strQD))
                {
                    List<GDSBInfo> list = m_DicSB[strQD];

                    for(int i = 0;i<list.Count;i++)
                    {
                        GDSBInfo pInfo = list[i];
                        Point2d ptE = Point2d.Origin;

                        GDSBInfo pInfoQD = m_DicSBInfo[strQD];

                        //不需要导线的设备
                        if (pInfo.strLY.Contains("byq")&& pInfoQD.strLY== "zy_dlskg")
                        {                          
                            CreateSB(btr, pInfo, ptS, ref ptE);

                            CreatePLine(btr, pInfo.strMC, ptE);
                        }
                        else if (pInfo.strLY.Contains("kg_")&&(pInfoQD.strLY == "zy_nz"|| pInfoQD.strLY == "zy_zx"))
                        {
                            CreateSB(btr, pInfo, ptS, ref ptE);

                            CreatePLine(btr, pInfo.strMC, ptE);
                        }
                        else
                        {
                            Point2d ptNS = Point2d.Origin;
                            CreateSB(btr, pInfo, ref ptE,ref ptNS);

                            Teigha.DatabaseServices.Polyline pLine = new Teigha.DatabaseServices.Polyline();
                            pLine.AddVertexAt(0, ptS, 0, 0, 0);
                            pLine.AddVertexAt(1, ptE, 0, 0, 0);

                            ObjectId Id = btr.AppendEntity(pLine);
                            GetExtent(pLine, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                            Entity pwEnt = null;
                            if (FindCADLayerByNM(m_pDb, "导线") == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = "导线";
                                if (pInfo.strLineType == "入地")
                                {
                                    pwEnt.Color = Color.FromColor(System.Drawing.Color.Blue);
                                }
                            }
                            //添加线长

                            if(!m_dicLXCD.Keys.Contains(pInfo.strMC))
                            {
                                m_dicLXCD.Add(pInfo.strMC, pLine.Length.ToString("F2") + "米");
                            }
                           

                            string strText = pLine.Length.ToString("F2") + "米";
                            if (!string.IsNullOrEmpty(pInfo.strLineTp))
                            {
                                strText = pInfo.strLineTp + "/" + strText;
                            }

                            if (!string.IsNullOrEmpty(pInfo.strLineType))
                            {
                                strText = strText + "(" + pInfo.strLineType + ")";
                            }
                            Point3d pt3dText = new Point3d((ptS.X + ptE.X) / 2, (ptS.Y + ptE.Y) / 2 + 0.1, 0);
                            DBText pText = CreateText(pt3dText, strText, "宋体");

                            pText.HorizontalMode = TextHorizontalMode.TextMid;
                            pText.VerticalMode = TextVerticalMode.TextBottom;
                            double rad = CalculateLineAngle(ptS, ptE);
                            pText.Height = 0.6;

                            pText.Rotation = rad;

                            Id = btr.AppendEntity(pText);
                            GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                            if (FindCADLayerByNM(m_pDb, "导线") == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = "导线";
                            }

                            if (m_dicTJXX.Keys.Contains("导线"))
                            {
                                double nSize = m_dicTJXX["导线"];
                                m_dicTJXX["导线"] = nSize + pLine.Length;
                            }
                            else
                            {
                                m_dicTJXX.Add("导线", pLine.Length);
                            }

                            CreatePLine(btr, pInfo.strMC, ptNS);

                        }
                    }                   
                }

            }
            catch (System.Exception ex)
            {
                return false;
            }

            return true;
        }

        private bool CreateSB(BlockTableRecord btr, GDSBInfo pInfo, ref Point2d ptE,ref Point2d ptS)
        {
            try
            {
                double x = 0;
                double y = 0;

                ObjectId BlkId = GetBlkIdByName(m_pDb, pInfo.strLY);
                if (BlkId == ObjectId.Null)
                {
                    BlkId = GetBlkIdByName(m_pDb, "zd");
                }

                ConvertPlaneCoord.MCT84Bl2xy(pInfo.lng, pInfo.lat, out x, out y);
                Point3d pt3D = new Point3d(y, x, 0);

                ptE = new Point2d(y, x);

                ptS = new Point2d(y, x);

                BlockReference blkRef = new BlockReference(pt3D, BlkId);
                if(pInfo.strLY == "zy_dlskg")
                {
                    blkRef.ScaleFactors = new Scale3d(0.2, 0.2, 0.2);
                }
                else if(pInfo.strLY.Contains("byq"))
                {
                    blkRef.ScaleFactors = new Scale3d(0.4, 0.4, 0.4);
                }
               
                ObjectId Id = btr.AppendEntity(blkRef);

                GetExtent(blkRef, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                if (pInfo.strLY == "zy_dlskg" || pInfo.strLY.Contains("kg_")|| pInfo.strLY==("zy_gybyq"))
                {
                    Extents3d exten = blkRef.GeometricExtents;

                    double xOff = (exten.MaxPoint.X - exten.MinPoint.X);

                    ptS = new Point2d(y + xOff, x);
                }

                Entity pwEnt = null;
                if (FindCADLayerByNM(m_pDb, "电力设备") == true)
                {
                    pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                    pwEnt.Layer = "电力设备";


                    HyperLinkCollection linkCollection = pwEnt.Hyperlinks;

                    //Create a new hyperlink

                    string strlinkPath = "配电设备\\" + pInfo.strMC + "全貌.jpg";
                    if (pInfo.strLY == "zy_nz" || pInfo.strLY == "zy_zx")
                    {
                        strlinkPath = "杆塔\\" + pInfo.strMC + "全貌.jpg";
                    }

                    HyperLink hyperLink = new HyperLink();

                    hyperLink.Description = strlinkPath;

                    hyperLink.Name = strlinkPath;

                    hyperLink.SubLocation = strlinkPath;

                    //Add the hyperlink to the collection

                    linkCollection.Add(hyperLink);

                }

                if (pInfo.strLY == "GDQZJ")
                {
                    Point3d pt3dText = new Point3d(y - 1.5, x - 0.3, 0);
                    DBText pText = CreateText(pt3dText, pInfo.strMC, "宋体");

                    pText.HorizontalMode = TextHorizontalMode.TextRight;
                    pText.VerticalMode = TextVerticalMode.TextTop;

                    Id = btr.AppendEntity(pText);
                    GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    if (FindCADLayerByNM(m_pDb, pInfo.strLY) == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = pInfo.strLY;
                    }
                }
                else if (pInfo.strLY == "GDJLX")
                {
                    Point3d pt3dText = new Point3d(y + 0.35, x + 0.006, 0);
                    DBText pText = CreateText(pt3dText, m_strNM + pInfo.strMC, "宋体");

                    pText.HorizontalMode = TextHorizontalMode.TextLeft;
                    pText.VerticalMode = TextVerticalMode.TextVerticalMid;

                    Id = btr.AppendEntity(pText);
                    GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    if (FindCADLayerByNM(m_pDb, pInfo.strLY) == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = pInfo.strLY;
                    }
                }
                else
                {
                    Point3d pt3dText = new Point3d(y, x + 0.5, 0);
                    DBText pText = CreateText(pt3dText, pInfo.strMC, "宋体");

                    pText.HorizontalMode = TextHorizontalMode.TextMid;
                    pText.VerticalMode = TextVerticalMode.TextVerticalMid;

                    Id = btr.AppendEntity(pText);
                    GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    if (FindCADLayerByNM(m_pDb, "设备名称") == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = "设备名称";

                        HyperLinkCollection linkCollection = pwEnt.Hyperlinks;

                        //Create a new hyperlink

                        string strlinkPath = "配电设备\\" + pInfo.strMC + "铭牌.jpg";

                        if (pInfo.strLY == "zy_nz" || pInfo.strLY == "zy_zx")
                        {
                            strlinkPath = "杆塔\\" + pInfo.strMC + "铭牌.jpg";

                            pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                        }

                        HyperLink hyperLink = new HyperLink();

                        hyperLink.Description = strlinkPath;

                        hyperLink.Name = strlinkPath;

                        hyperLink.SubLocation = strlinkPath;

                        //Add the hyperlink to the collection

                        linkCollection.Add(hyperLink);
                    }

                }
            }
            catch (System.Exception ex)
            {
                return false;
            }
            return true;
        }
        private bool CreateSB(BlockTableRecord btr,GDSBInfo pInfo, Point2d ptS,ref Point2d pt)
        {
            try
            {

                ObjectId BlkId = GetBlkIdByName(m_pDb, pInfo.strLY);
                if (BlkId == ObjectId.Null)
                {
                    BlkId = GetBlkIdByName(m_pDb, "zd");
                }

                Point3d pt3D = new Point3d(ptS.X, ptS.Y, 0);

                BlockReference blkRef = new BlockReference(pt3D, BlkId);
                if (pInfo.strLY == "zy_dlskg")
                {
                    blkRef.ScaleFactors = new Scale3d(0.2, 0.2, 0.2);
                }
                else if (pInfo.strLY.Contains("gybyq"))
                {
                    blkRef.ScaleFactors = new Scale3d(0.4, 0.4, 0.4);
                }
                ObjectId Id = btr.AppendEntity(blkRef);

                GetExtent(blkRef, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);
              
                Extents3d exten = blkRef.GeometricExtents;
                double xOff = (exten.MaxPoint.X - exten.MinPoint.X);

                pt = new Point2d(pt3D.X + xOff, pt3D.Y);

                Entity pwEnt = null;
                if (FindCADLayerByNM(m_pDb, "电力设备") == true)
                {
                    pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                    pwEnt.Layer = "电力设备";

                    HyperLinkCollection linkCollection = pwEnt.Hyperlinks;

                    //Create a new hyperlink

                    string strlinkPath = "配电设备\\" + pInfo.strMC + "全貌.jpg";
                    if(pInfo.strLY== "zy_nz"|| pInfo.strLY == "zy_zx")
                    {
                        strlinkPath = "杆塔\\" + pInfo.strMC + "全貌.jpg";
                    }

                    HyperLink hyperLink = new HyperLink();

                    hyperLink.Description = strlinkPath;

                    hyperLink.Name = strlinkPath;

                    hyperLink.SubLocation = strlinkPath;

                    //Add the hyperlink to the collection

                    linkCollection.Add(hyperLink);

                }        

           
                {
                    Point3d pt3dText = new Point3d(ptS.X,ptS.Y + 0.5, 0);
                    DBText pText = CreateText(pt3dText, pInfo.strMC, "宋体");

                    pText.HorizontalMode = TextHorizontalMode.TextMid;
                    pText.VerticalMode = TextVerticalMode.TextVerticalMid;

                    Id = btr.AppendEntity(pText);
                    GetExtent(pText, ref m_xMin, ref m_xMax, ref m_yMin, ref m_yMax);

                    if (FindCADLayerByNM(m_pDb, "设备名称") == true)
                    {
                        pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                        pwEnt.Layer = "设备名称";

                        HyperLinkCollection linkCollection = pwEnt.Hyperlinks;

                        //Create a new hyperlink

                        string strlinkPath = "配电设备\\" + pInfo.strMC + "铭牌.jpg";

                        if (pInfo.strLY == "zy_nz" || pInfo.strLY == "zy_zx")
                        {
                            strlinkPath = "杆塔\\" + pInfo.strMC + "铭牌.jpg";

                            pwEnt.Color = Color.FromColor(System.Drawing.Color.Red);
                        }

                        HyperLink hyperLink = new HyperLink();

                        hyperLink.Description = strlinkPath;

                        hyperLink.Name = strlinkPath;

                        hyperLink.SubLocation = strlinkPath;

                        //Add the hyperlink to the collection

                        linkCollection.Add(hyperLink);
                    }

                }
            }
            catch(System.Exception ex)
            {
                return false;
            }
            return true;
        }

        private double CalculateLineAngle(Point2d pt1, Point2d pt2)
        {
            double J = 0;
            double x = pt2.X - pt1.X;
            double y = pt2.Y - pt1.Y;

            if (x == 0 && y < 0)
            {
                J = 0;
            }
            else
            {
                double k = y / x;
                J = Math.Atan2(y, x); //弧度
            }

            double ang = J * 180.0 / Math.PI; //角度

            if (ang < 0)
            {
                ang = ang + 360;
            }

            if (ang == 0)
            {
                ang = 270;
            }

            if (ang > 90 && ang <= 180)
            {
                ang = ang + 180;
            }
            else if (ang > 180 && ang < 270)
            {
                ang = ang - 180;
            }

            double rad = ang * Math.PI / 180;

            return rad;
        }

        private ObjectId GetTextStyleIdByName(Database pDb, string strName)
        {
            ObjectId Oid = ObjectId.Null;
            try
            {
                using (TextStyleTable styleTable = (TextStyleTable)pDb.TextStyleTableId.GetObject(OpenMode.ForRead))
                {
                    foreach (ObjectId id in styleTable)
                    {
                        using (TextStyleTableRecord pTextStyle = (TextStyleTableRecord)id.Open(OpenMode.ForRead))
                        {
                            if (pTextStyle.Name == strName)
                            {
                                Oid = id;
                                break;
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
            return Oid;
        }

        private DBText CreateText(Point3d pt, string strText, string strTextStyleName)
        {
            DBText pText = new DBText();
            pText.Position = pt;
            pText.TextString = strText;

            ObjectId styleId = GetTextStyleIdByName(m_pDb, strTextStyleName);
            pText.TextStyleId = styleId;
            pText.Height = 0.6;
            pText.Rotation = 0;
            pText.WidthFactor = 1;
            pText.Oblique = 0;
            pText.VerticalMode = TextVerticalMode.TextVerticalMid;
            pText.HorizontalMode = TextHorizontalMode.TextCenter;

            pText.AlignmentPoint = pt;
            pText.AdjustAlignment(m_pDb);//设置文字对齐


            return pText;
        }

        private ObjectId GetBlkIdByName(Database pDb, string strName)
        {
            ObjectId Oid = ObjectId.Null;
            try
            {
                TransactionManager pTMgr = pDb.TransactionManager;
                using (Transaction pTransac = pTMgr.StartTransaction())
                {
                    BlockTable pBTable = pTMgr.GetObject(pDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                    foreach (ObjectId id in pBTable)
                    {

                        BlockTableRecord pBlock = pTMgr.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
                        string str = pBlock.Name;
                        if (pBlock.Name == strName)
                        {
                            Oid = id;
                            break;
                        }

                        // m_Dic.Add(str, id);
                    }

                    pTransac.Commit();
                }



            }
            catch (System.Exception ex)
            {

            }
            //  m_Dic.Add("9999", Oid);
            return Oid;
        }

        public bool FindCADLayerByNM(Database pDB, string strName)
        {

            if (pDB == null) return false;

            try
            {
                TransactionManager pTMgr = pDB.TransactionManager;
                using (Transaction pTransac = pTMgr.StartTransaction())
                {
                    LayerTable pLayerTable = pTMgr.GetObject(pDB.LayerTableId, OpenMode.ForRead) as LayerTable;

                    SymbolTableEnumerator pIterator = pLayerTable.GetEnumerator();

                    while (pIterator.MoveNext())
                    {
                        ObjectId objId = pIterator.Current;
                        LayerTableRecord pLayer = pTMgr.GetObject(objId, OpenMode.ForRead) as LayerTableRecord;

                        string strLy = pLayer.Name;

                        if (strLy == strName)
                        {
                            pTransac.Commit();
                            return true;
                        }

                    }

                    pTransac.Commit();
                }
                return false;
            }
            catch (System.Exception ex)
            {
                return false;
            }

        }

        private bool GetExtent(Entity pEnt,ref double xMin, ref double xMax, ref double yMin, ref double yMax)
        {
            try
            {
                if(pEnt==null)
                {
                    return false;
                }

                Extents3d exten = pEnt.GeometricExtents;
                Point3d pt1 = exten.MinPoint;
                Point3d pt2 = exten.MaxPoint;

                if(xMin==0)
                {
                    xMin = pt1.X;
                }

                if (yMin == 0)
                {
                    yMin = pt1.Y;
                }

                if (pt1.X< xMin)
                {
                    xMin = pt1.X;
                }

                if(pt1.Y < yMin)
                {
                    yMin = pt1.Y;
                }

                if (pt2.X >xMax)
                {
                    xMax = pt2.X;
                }

                if (pt2.Y > yMax)
                {
                    yMax = pt2.Y;
                }

            }
            catch(System.Exception ex)
            {
                return false;
            }
            return true;
        }

        public bool SaveToExcel(string strPath)
        {
            try
            {
                IWorkbook  workbook = NPOIExcelHelper.CreateWorkbook();
                ISheet sheet = NPOIExcelHelper.CreateSheetByName(workbook, "杆塔及隐患缺陷类型核查表");
                CreateTableProduct( workbook, sheet, "配电线路、配电房等隐患排查表");

                sheet = NPOIExcelHelper.CreateSheetByName(workbook, "柱上变、开关、配电站房等设备核查表");
                CreateTableMarket(workbook, sheet, "柱上变、开关、配电站房等设备核查表核查情况统计表");

                NPOIExcelHelper.SaveExcel(workbook, strPath);
            }
            catch(System.Exception ex)
            {
                return false;
            }
            return true;
        }

        public bool CreateTableProduct(IWorkbook workbook, ISheet worksheet, string strTabName)
        {
            try
            {
                if (worksheet != null)
                {
                    ICell sheetTitle = worksheet.CreateRow(0).CreateCell(0);                   
                    sheetTitle.SetCellValue(strTabName);
                    sheetTitle.CellStyle = NPOIExcelHelper.GetTitleCellStyle(workbook, 15, NPOI.HSSF.Util.HSSFColor.Black.Index);
                    worksheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 8));  //合并单元格

                    //string str = "台区：" + m_strNM;
                    //ICell sheetTitle1 = worksheet.CreateRow(1).CreateCell(0);                   

                    //sheetTitle1.SetCellValue(str);
                    //sheetTitle1.CellStyle = NPOIExcelHelper.GetTitleCellStyle(workbook, 13, NPOI.HSSF.Util.HSSFColor.Black.Index);
                    //worksheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 0, 8));  //合并单元格

                    IRow sheetHead = worksheet.CreateRow(1);

                    //表头数据
                    ICellStyle cellStyle1 = NPOIExcelHelper.GetCellStyle(workbook, 2);
                    ICellStyle cellStyle2 = NPOIExcelHelper.GetCellStyle(workbook, 0);

                    ICell cell = sheetHead.CreateCell(0);
                    cell.SetCellValue("序号");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(1);
                    cell.SetCellValue("设备名称");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(2);
                    cell.SetCellValue("所属线路");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(3);
                    cell.SetCellValue("杆塔材质");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(4);
                    cell.SetCellValue("设备类型");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(5);
                    cell.SetCellValue("杆塔性质");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(6);
                    cell.SetCellValue("杆塔型号");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(7);
                    cell.SetCellValue("是否终端");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(8);
                    cell.SetCellValue("经度");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(9);
                    cell.SetCellValue("纬度");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(10);
                    cell.SetCellValue("隐患");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(11);
                    cell.SetCellValue("缺陷情况");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(12);
                    cell.SetCellValue("数量");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(13);
                    cell.SetCellValue("线路巡视检查人员");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(14);
                    cell.SetCellValue("长度");
                    cell.CellStyle = cellStyle1;

                    for (int i = 0;i< m_listGTCheck.Count;i++)
                    {
                        GTCheckTab pInfo = m_listGTCheck[i];
                        IRow row = worksheet.CreateRow(2+i);

                        cell = row.CreateCell(0);
                        cell.SetCellValue(i+1);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(1);
                        cell.SetCellValue(pInfo.strName);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(2);
                        cell.SetCellValue(pInfo.strSSXL);                                  
                        cell.CellStyle = cellStyle2;
                    
                        cell = row.CreateCell(3);
                        cell.SetCellValue(pInfo.strCZ);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(4);
                        cell.SetCellValue(pInfo.strType);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(5);
                        cell.SetCellValue(pInfo.strXZ);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(6);
                        cell.SetCellValue(pInfo.strXH);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(7);
                        cell.SetCellValue(pInfo.strZD);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(8);
                        cell.SetCellValue(pInfo.strLng);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(9);
                        cell.SetCellValue(pInfo.strLat);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(10);
                        cell.SetCellValue(pInfo.strYH);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(11);
                        cell.SetCellValue(pInfo.strQX);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(12);
                        cell.SetCellValue(pInfo.strSL);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(13);
                        cell.SetCellValue(pInfo.strXCRY);
                        cell.CellStyle = cellStyle2;


                        if (m_dicLXCD.Keys.Contains(pInfo.strName))
                        {
                            cell = row.CreateCell(14);
                            cell.SetCellValue(m_dicLXCD[pInfo.strName]);
                            cell.CellStyle = cellStyle2;                         
                        }

                    }

                }
            }
            catch (System.Exception ex)
            {
                return false;
            }

            return true;
        }

        public bool CreateTableMarket(IWorkbook workbook, ISheet worksheet, string strTabName)
        {
            try
            {
                if (worksheet != null)
                {
                    ICell sheetTitle = worksheet.CreateRow(0).CreateCell(0);
                    sheetTitle.SetCellValue(strTabName);
                    sheetTitle.CellStyle = NPOIExcelHelper.GetTitleCellStyle(workbook, 15, NPOI.HSSF.Util.HSSFColor.Black.Index);
                    worksheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 8));  //合并单元格

                    //string str = "台区：" + m_strNM;
                    //ICell sheetTitle1 = worksheet.CreateRow(1).CreateCell(0);
                    //sheetTitle1.SetCellValue(str);
                    //sheetTitle1.CellStyle = NPOIExcelHelper.GetTitleCellStyle(workbook, 13, NPOI.HSSF.Util.HSSFColor.Black.Index);
                    //worksheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 0, 8));  //合并单元格

                    IRow sheetHead = worksheet.CreateRow(1);

                    //表头数据
                    ICellStyle cellStyle1 = NPOIExcelHelper.GetCellStyle(workbook, 2);
                    ICellStyle cellStyle2 = NPOIExcelHelper.GetCellStyle(workbook, 0);

                    ICell cell = sheetHead.CreateCell(0);
                    cell.SetCellValue("序号");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(1);
                    cell.SetCellValue("设备名称");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(2);
                    cell.SetCellValue("设备类型");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(3);
                    cell.SetCellValue("设备状态");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(4);
                    cell.SetCellValue("所属馈线");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(5);
                    cell.SetCellValue("资产状态");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(6);
                    cell.SetCellValue("设备型号");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(7);
                    cell.SetCellValue("变压器额定容量(kVA)");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(8);
                    cell.SetCellValue("现场所在杆号");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(9);
                    cell.SetCellValue("现场开合闸情况");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(10);
                    cell.SetCellValue("缺陷情况");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(11);
                    cell.SetCellValue("异常原因");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(12);
                    cell.SetCellValue("经度");
                    cell.CellStyle = cellStyle1;

                    cell = sheetHead.CreateCell(13);
                    cell.SetCellValue("纬度");
                    cell.CellStyle = cellStyle1;

                    for (int i = 0; i < m_listSBCheck.Count; i++)
                    {
                        SBCheckTab pInfo = m_listSBCheck[i];

                        IRow row = worksheet.CreateRow(i + 2);

                        cell = row.CreateCell(0);
                        cell.SetCellValue(i + 1);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(1);
                        cell.SetCellValue(pInfo.strName);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(2);
                        cell.SetCellValue(pInfo.strType);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(3);
                        cell.SetCellValue(pInfo.strZT);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(4);
                        cell.SetCellValue(pInfo.strSSXL);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(5);
                        cell.SetCellValue(pInfo.strZC);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(6);
                        cell.SetCellValue(pInfo.strXH);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(7);
                        cell.SetCellValue(pInfo.strRL);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(8);
                        cell.SetCellValue(pInfo.strGH);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(9);
                        cell.SetCellValue(pInfo.strKH);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(10);
                        cell.SetCellValue(pInfo.strQX);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(11);
                        cell.SetCellValue(pInfo.strYY);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(12);
                        cell.SetCellValue(pInfo.strLng);
                        cell.CellStyle = cellStyle2;

                        cell = row.CreateCell(13);
                        cell.SetCellValue(pInfo.strLat);
                        cell.CellStyle = cellStyle2;

                    }

                }
            }
            catch (System.Exception ex)
            {
                return false;
            }

            return true;
        }

  

    }
}
